package org.jeecg.modules.system.controller;


import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.AntPathMatcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import java.net.MalformedURLException;

/**
 * @author 贾振华
 */
@RestController
@RequestMapping("/minioFile")
@Log
@Slf4j
public class FileProxyController {
    @Value(value = "${jeecg.minio.minio_url}")
    private String url;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @GetMapping("/**")
    public ResponseEntity<Resource> proxyFileRequest(HttpServletRequest request) throws MalformedURLException {
        // 获取完整的路径
        String uri = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        // 获取映射的路径
        String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        // 截取带“/”的参数
        String customPath = antPathMatcher.extractPathWithinPattern(pattern,uri);
       log.info("=======url============"+url);
        String minioUrl = url + "/" + customPath;
        Resource resource = new UrlResource(minioUrl);

        if (resource.exists() || resource.isReadable()) {
            MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
            String fileExtension = "";
            // 获取文件后缀名
            int lastIndexOfDot = customPath.lastIndexOf('.');
            fileExtension = customPath.substring(lastIndexOfDot + 1);

            if (customPath.contains("htm")) {
                mediaType = MediaType.TEXT_HTML;
            } else {
                mediaType = MediaType.parseMediaType("application/octet-stream");

                switch (fileExtension.toLowerCase()) {
                    case "pdf":
                        mediaType = MediaType.APPLICATION_PDF;
                        break;
                    case "jpeg":
                    case "jpg":
                        mediaType = MediaType.IMAGE_JPEG;
                        break;
                    case "svg":
                        mediaType = MediaType.valueOf("image/svg+xml");
                        break;
                    case "png":
                        mediaType = MediaType.IMAGE_PNG;
                        break;
                    // 可以添加更多case来处理其他类型的文件
                }
            }

            // 对于非HTML文件，要设置Content-Disposition为inline（可选）
            HttpHeaders headers = new HttpHeaders();
            if (!"text/html".equals(mediaType.toString())) {
                String filename = customPath.substring(customPath.lastIndexOf('/') + 1);
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"");
            }

            return ResponseEntity.ok()
                    .contentType(mediaType)
                    .headers(headers)
                    .body(resource);
        } else {
            log.info("========return==========="+ ResponseEntity.notFound().build());
            return ResponseEntity.notFound().build();
        }
    }

}
